<template>
  <div>
    <h2>用户页面</h2>
    <el-input placeholder="请输入" v-model="message"></el-input>
    <el-button @click="send">发送</el-button>
    展示聊天内容：
    <ul>
        <li v-for="i in meslist">{{i}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ws: "",
      userid: localStorage.getItem("userid"),
      mobile: localStorage.getItem("mobile"),
      message:'',
      meslist:[],
    };
  },
  methods: {
    initWebsocket() {
      this.ws = new WebSocket(
        "ws://localhost:8000/webuser?id=" +
          this.userid +
          "&mobile=" +
          this.mobile
      );
      this.ws.onopen = function () {
        alert("success");
      };
      this.ws.onmessage = (data) => {
        console.log(data.data);
        var mes = JSON.parse(data.data);
        this.meslist.push(mes['mes'])
      };

      this.ws.onclose = function () {
        alert("close");
      };
    },
    send(){
        var mes = this.mobile + '说:' + this.message
        this.meslist.push(mes)
        var sendmes = JSON.stringify({'id':'kefu','mes':mes})
        this.ws.send(sendmes)
    }
  },
  mounted() {
    this.initWebsocket();
  },
};
</script>

<style>
</style>